package utils

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type respData struct {
	Code   int         `json:"code"`
	Status string      `json:"status"`
	Error  interface{} `json:"error,omitempty"`
	Tip    string      `json:"tip,omitempty"`
	Data   interface{} `json:"data,omitempty"`
	Token  interface{} `json:"token,omitempty"`
}

type PageData struct {
	List  interface{} `json:"list"`
	Count int         `json:"count"`
}

func OverSpeed(ctx *gin.Context) {
	code := http.StatusNotAcceptable
	ctx.JSON(code, http.StatusText(code))
	ctx.Abort()
}

func Success(ctx *gin.Context, data interface{}) {
	code := http.StatusOK
	resp := respData{
		Code:   code,
		Status: http.StatusText(code),
		Data:   data,
	}
	if token, ok := ctx.Get("token"); ok {
		resp.Token = token
	}
	ctx.JSON(code, resp)
}

func Unauthorized(ctx *gin.Context, msg interface{}) {
	code := http.StatusUnauthorized
	resp := respData{
		Code:   code,
		Status: http.StatusText(code),
		Error:  msg,
	}
	ctx.JSON(code, resp)
	ctx.Abort()
}

func Fail(ctx *gin.Context, err error, tip ...string) {
	code := http.StatusInternalServerError
	resp := respData{
		Code:   code,
		Status: http.StatusText(code),
		Error:  err.Error(),
	}
	if len(tip) > 0 {
		resp.Tip = tip[0]
	}
	if token, ok := ctx.Get("token"); ok {
		resp.Token = token
	}
	ctx.JSON(code, resp)
	ctx.Abort()
}

func Redirect(ctx *gin.Context, url string) {
	code := http.StatusPermanentRedirect
	resp := respData{
		Code:   code,
		Status: http.StatusText(code),
	}
	if token, ok := ctx.Get("token"); ok {
		resp.Token = token
	}
	ctx.Redirect(code, url)
}
